package database

import (
	"fmt"
	"log"
	"strconv"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/config"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

// Init 初始化数据库连接
func Init() error {
	// 检查配置
	if config.GlobalConfig.Database.Username == "" {
		return fmt.Errorf("database username is empty")
	}
	if config.GlobalConfig.Database.Password == "" {
		return fmt.Errorf("database password is empty")
	}
	if config.GlobalConfig.Database.Host == "" {
		return fmt.Errorf("database host is empty")
	}
	if config.GlobalConfig.Database.Port == "" {
		return fmt.Errorf("database port is empty")
	}
	if config.GlobalConfig.Database.DBName == "" {
		return fmt.Errorf("database name is empty")
	}

	// 将端口字符串转换为整数
	port, err := strconv.Atoi(config.GlobalConfig.Database.Port)
	if err != nil {
		return fmt.Errorf("invalid database port: %v", err)
	}

	// 打印数据库配置信息（隐藏密码）
	log.Printf("Database config - Host: %s, Port: %d, User: %s, Database: %s",
		config.GlobalConfig.Database.Host,
		port,
		config.GlobalConfig.Database.Username,
		config.GlobalConfig.Database.DBName,
	)

	// 构建DSN
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=%v&loc=%s",
		config.GlobalConfig.Database.Username,
		config.GlobalConfig.Database.Password,
		config.GlobalConfig.Database.Host,
		port,
		config.GlobalConfig.Database.DBName,
		config.GlobalConfig.Database.Charset,
		config.GlobalConfig.Database.ParseTime,
		config.GlobalConfig.Database.Loc,
	)

	// 打印DSN（隐藏密码）
	log.Printf("DSN: %s:******@tcp(%s:%d)/%s?charset=%s&parseTime=%v&loc=%s",
		config.GlobalConfig.Database.Username,
		config.GlobalConfig.Database.Host,
		port,
		config.GlobalConfig.Database.DBName,
		config.GlobalConfig.Database.Charset,
		config.GlobalConfig.Database.ParseTime,
		config.GlobalConfig.Database.Loc,
	)

	// 配置GORM日志
	newLogger := logger.New(
		log.New(log.Writer(), "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             time.Second,
			LogLevel:                  logger.Info,
			IgnoreRecordNotFoundError: true,
			Colorful:                  true,
		},
	)

	var dbErr error
	DB, dbErr = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if dbErr != nil {
		return fmt.Errorf("failed to connect to database: %v", dbErr)
	}

	// 设置连接池
	sqlDB, err := DB.DB()
	if err != nil {
		return fmt.Errorf("failed to get database instance: %v", err)
	}

	// 设置连接池参数
	sqlDB.SetMaxIdleConns(5)                   // 减少空闲连接数
	sqlDB.SetMaxOpenConns(20)                  // 减少最大连接数
	sqlDB.SetConnMaxLifetime(30 * time.Minute) // 减少连接最大生命周期
	sqlDB.SetConnMaxIdleTime(10 * time.Minute) // 添加空闲连接最大生命周期

	log.Printf("Successfully connected to MySQL database: %s:%d/%s",
		config.GlobalConfig.Database.Host,
		port,
		config.GlobalConfig.Database.DBName,
	)
	return nil
}

// Close 关闭数据库连接
func Close() error {
	if DB != nil {
		sqlDB, err := DB.DB()
		if err != nil {
			return err
		}
		return sqlDB.Close()
	}
	return nil
}
